package com.jiguiquan.www.controller;

import com.jiguiquan.starter.common.vo.BaseResponse;
import com.jiguiquan.www.service.JsInvokeService;
import com.jiguiquan.www.service.MyJsScriptEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author jiguiquan
 * @Email jiguiquan@haier.com
 * @Data 2023-06-30 13:45
 */
@RestController
@RequestMapping("/js")
public class JsScriptController {
    public static final String js1 = "return m + n";
    public static final String js2 = "return m - n";
    public static final String js3 = "return m * n";
    public static final String js4 = "return m / n";

    private ConcurrentHashMap<String,MyJsScriptEngine > myEngineMap = new ConcurrentHashMap<>();

    @Autowired
    private JsInvokeService jsInvokeService;

    @PostConstruct
    public void init(){
        myEngineMap.put("js1", new MyJsScriptEngine(jsInvokeService, js1));
        myEngineMap.put("js2", new MyJsScriptEngine(jsInvokeService, js2));
        myEngineMap.put("js3", new MyJsScriptEngine(jsInvokeService, js3));
        myEngineMap.put("js4", new MyJsScriptEngine(jsInvokeService, js4));
    }

    @GetMapping("/js1")
    private BaseResponse testEval1(Integer a, Integer b){
        return BaseResponse.success(myEngineMap.get("js1").invoke(a, b));
    }

    @GetMapping("/js2")
    private BaseResponse testEval2(Integer a, Integer b){
        return BaseResponse.success(myEngineMap.get("js2").invoke(a, b));
    }

    @GetMapping("/js3")
    private BaseResponse testEval3(Integer a, Integer b){
        return BaseResponse.success(myEngineMap.get("js3").invoke(a, b));
    }

    @GetMapping("/js4")
    private BaseResponse testEval4(Integer a, Integer b){
        return BaseResponse.success(myEngineMap.get("js4").invoke(a, b));
    }

}
